<template>
  <div id="animation"></div>
</template>

<script setup>
import { onMounted, render } from 'vue'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'

const scene = new THREE.Scene()
const geometry = new THREE.BoxGeometry(200, 200, 200)
const material = new THREE.MeshBasicMaterial({ color: 'pink' })
const mesh = new THREE.Mesh(geometry, material)
mesh.position.set(0, 0, 0)

scene.add(mesh)
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.set(0, 0, 1000)

const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)

const animate = () => {
  requestAnimationFrame(animate)
  /**
   * 旋转 rotation 的 x 和 y
   * x代表绕x轴旋转，y代表绕y轴旋转
   * 0.01 代表旋转的弧度
   */
  mesh.rotation.x += 0.01
  mesh.rotation.y += 0.01
  mesh.rotation.z += 0.01
  renderer.render(scene, camera)
}

/**
 * canvas 画布宽高动态变化时需要更新相机和渲染的参数，否则无法正常显示
 */
window.onresize = () => {
  // 更新渲染器的尺寸
  renderer.setSize(window.innerWidth, window.innerHeight)
  // 更新相机的宽高比
  camera.aspect = window.innerWidth / window.innerHeight
  // 更新相机的投影矩阵
  camera.updateProjectionMatrix()
}
onMounted(() => {
  /**
   * 设置了渲染循环，相机控件就不用通过手动更新来实现了，因为渲染循环会自动更新相机控件
   */
  new OrbitControls(camera, renderer.domElement)
  // controls.update()
  document.getElementById('animation').appendChild(renderer.domElement)
  animate()
})
</script>

<style>

</style>